﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CLEXA.ClientTools.Collections;
using CLEXA.DataContracts;
using CLEXA.ServiceContracts;

namespace CLEXA.SurfaceClient.Cache
{
    public class DatabaseCache : IDatabaseCache
    {
        private readonly IClientService clientService;
        private readonly int userId;
        private readonly ObservableDictionary<int, DatabaseData> databases;
        private readonly ReadOnlyObservableDictionary<int, DatabaseData> databasesReadOnly;

        public int UserId
        {
            get { return userId; }
        } 

        public IReadOnlyObservableDictionary<int, DatabaseData> Databases
        {
            get { return databasesReadOnly; }
        }

        public DatabaseCache(IClientService clientService, int userId)
        {
            this.clientService = clientService;
            this.userId = userId;
            this.databases = new ObservableDictionary<int, DatabaseData>(this.clientService.GetDatabasesByUserId(this.userId), p => p.DatabaseId);
            this.databasesReadOnly = new ReadOnlyObservableDictionary<int, DatabaseData>(this.databases);
        }

        public void UpdateDatabase(DatabaseData database)
        {
            clientService.UpdateDatabase(database);
            databases[database.DatabaseId] = database;
        }

        public void DeleteDatabase(int databaseId)
        {
            clientService.DeleteDatabase(databaseId);
            databases.Remove(databaseId);
        }

        public int CreateDatabase(int userId, string connectionString)
        {
            int databaseId = clientService.CreateDatabase(userId, connectionString);
            databases.Add(databaseId, new DatabaseData(databaseId, userId, connectionString));
            return databaseId;
        }
    }
}
